package com.hck.trigger.http;

import com.hck.domain.health.model.entity.*;
import com.hck.domain.health.service.IHealthService;
import com.hck.types.model.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 健康管理Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/health")
@Tag(name = "健康管理", description = "健康档案、检查记录、报告、预警等")
public class HealthController {

    @Resource
    private IHealthService healthService;

    // ==================== 健康档案相关 ====================
    
    @GetMapping("/profile/{userId}")
    @Operation(summary = "获取健康档案", description = "根据用户ID获取健康档案信息")
    public Response<HealthProfileEntity> getHealthProfile(@PathVariable Long userId) {
        HealthProfileEntity profile = healthService.getHealthProfile(userId);
        if (profile != null) {
            return Response.<HealthProfileEntity>builder()
                    .code("200")
                    .data(profile)
                    .info("获取成功")
                    .build();
        } else {
            return Response.<HealthProfileEntity>builder()
                    .code("404")
                    .data(null)
                    .info("健康档案不存在")
                    .build();
        }
    }

    @PostMapping("/profile")
    @Operation(summary = "创建健康档案", description = "创建新的健康档案")
    public Response<Boolean> createHealthProfile(@RequestBody HealthProfileEntity profile) {
        try {
            healthService.saveHealthProfile(profile);
            return Response.<Boolean>builder()
                    .code("200")
                    .data(true)
                    .info("创建成功")
                    .build();
        } catch (Exception e) {
            log.error("创建健康档案失败", e);
            return Response.<Boolean>builder()
                    .code("500")
                    .data(false)
                    .info("创建失败：" + e.getMessage())
                    .build();
        }
    }

    @PutMapping("/profile")
    @Operation(summary = "更新健康档案", description = "更新现有健康档案")
    public Response<Boolean> updateHealthProfile(@RequestBody HealthProfileEntity profile) {
        try {
            healthService.updateHealthProfile(profile);
            return Response.<Boolean>builder()
                    .code("200")
                    .data(true)
                    .info("更新成功")
                    .build();
        } catch (Exception e) {
            log.error("更新健康档案失败", e);
            return Response.<Boolean>builder()
                    .code("500")
                    .data(false)
                    .info("更新失败：" + e.getMessage())
                    .build();
        }
    }

    // ==================== 健康检查记录相关 ====================
    
    @PostMapping("/check-record")
    @Operation(summary = "添加健康检查记录", description = "添加新的健康检查记录")
    public Response<Boolean> addHealthCheckRecord(@RequestBody HealthCheckRecordEntity record) {
        try {
            healthService.addHealthCheckRecord(record);
            // 添加记录后自动检查是否需要生成预警
            healthService.checkAndGenerateAlerts(record.getUserId());
            return Response.<Boolean>builder()
                    .code("200")
                    .data(true)
                    .info("添加成功")
                    .build();
        } catch (Exception e) {
            log.error("添加健康检查记录失败", e);
            return Response.<Boolean>builder()
                    .code("500")
                    .data(false)
                    .info("添加失败：" + e.getMessage())
                    .build();
        }
    }

    @GetMapping("/check-records/{userId}")
    @Operation(summary = "获取健康检查记录", description = "根据用户ID和检查类型获取健康检查记录")
    public Response<List<HealthCheckRecordEntity>> getHealthCheckRecords(
            @PathVariable Long userId,
            @RequestParam(required = false) String checkType) {
        List<HealthCheckRecordEntity> records = healthService.getHealthCheckRecords(userId, checkType);
        return Response.<List<HealthCheckRecordEntity>>builder()
                .code("200")
                .data(records)
                .info("获取成功")
                .build();
    }

    @GetMapping("/check-record/latest/{userId}")
    @Operation(summary = "获取最新健康检查记录", description = "获取用户最新的健康检查记录")
    public Response<HealthCheckRecordEntity> getLatestHealthCheckRecord(
            @PathVariable Long userId,
            @RequestParam String checkType) {
        HealthCheckRecordEntity record = healthService.getLatestHealthCheckRecord(userId, checkType);
        if (record != null) {
            return Response.<HealthCheckRecordEntity>builder()
                    .code("200")
                    .data(record)
                    .info("获取成功")
                    .build();
        } else {
            return Response.<HealthCheckRecordEntity>builder()
                    .code("404")
                    .data(null)
                    .info("暂无检查记录")
                    .build();
        }
    }

    // ==================== 健康报告相关 ====================
    
    @PostMapping("/report/generate/{userId}")
    @Operation(summary = "生成健康报告", description = "根据用户健康数据生成健康报告")
    public Response<HealthReportEntity> generateHealthReport(@PathVariable Long userId) {
        try {
            HealthReportEntity report = healthService.generateHealthReport(userId);
            return Response.<HealthReportEntity>builder()
                    .code("200")
                    .data(report)
                    .info("生成成功")
                    .build();
        } catch (Exception e) {
            log.error("生成健康报告失败", e);
            return Response.<HealthReportEntity>builder()
                    .code("500")
                    .data(null)
                    .info("生成失败：" + e.getMessage())
                    .build();
        }
    }

    @GetMapping("/reports/{userId}")
    @Operation(summary = "获取健康报告列表", description = "获取用户的所有健康报告")
    public Response<List<HealthReportEntity>> getHealthReports(@PathVariable Long userId) {
        List<HealthReportEntity> reports = healthService.getHealthReports(userId);
        return Response.<List<HealthReportEntity>>builder()
                .code("200")
                .data(reports)
                .info("获取成功")
                .build();
    }

    @GetMapping("/report/{reportId}")
    @Operation(summary = "获取健康报告详情", description = "根据报告ID获取健康报告详情")
    public Response<HealthReportEntity> getHealthReportById(@PathVariable Long reportId) {
        HealthReportEntity report = healthService.getHealthReportById(reportId);
        if (report != null) {
            return Response.<HealthReportEntity>builder()
                    .code("200")
                    .data(report)
                    .info("获取成功")
                    .build();
        } else {
            return Response.<HealthReportEntity>builder()
                    .code("404")
                    .data(null)
                    .info("报告不存在")
                    .build();
        }
    }

    // ==================== 健康预警相关 ====================
    
    @GetMapping("/alerts/{userId}")
    @Operation(summary = "获取健康预警列表", description = "获取用户的所有健康预警")
    public Response<List<HealthAlertEntity>> getHealthAlerts(@PathVariable Long userId) {
        List<HealthAlertEntity> alerts = healthService.getHealthAlerts(userId);
        return Response.<List<HealthAlertEntity>>builder()
                .code("200")
                .data(alerts)
                .info("获取成功")
                .build();
    }

    @GetMapping("/alerts/unread/{userId}")
    @Operation(summary = "获取未读健康预警", description = "获取用户的未读健康预警")
    public Response<List<HealthAlertEntity>> getUnreadAlerts(@PathVariable Long userId) {
        List<HealthAlertEntity> alerts = healthService.getUnreadAlerts(userId);
        return Response.<List<HealthAlertEntity>>builder()
                .code("200")
                .data(alerts)
                .info("获取成功")
                .build();
    }

    @PutMapping("/alert/read/{alertId}")
    @Operation(summary = "标记预警为已读", description = "将健康预警标记为已读")
    public Response<Boolean> markAlertAsRead(@PathVariable Long alertId) {
        try {
            healthService.markAlertAsRead(alertId);
            return Response.<Boolean>builder()
                    .code("200")
                    .data(true)
                    .info("标记成功")
                    .build();
        } catch (Exception e) {
            log.error("标记预警为已读失败", e);
            return Response.<Boolean>builder()
                    .code("500")
                    .data(false)
                    .info("标记失败：" + e.getMessage())
                    .build();
        }
    }

    @PutMapping("/alert/handle/{alertId}")
    @Operation(summary = "标记预警为已处理", description = "将健康预警标记为已处理")
    public Response<Boolean> markAlertAsHandled(@PathVariable Long alertId) {
        try {
            healthService.markAlertAsHandled(alertId);
            return Response.<Boolean>builder()
                    .code("200")
                    .data(true)
                    .info("标记成功")
                    .build();
        } catch (Exception e) {
            log.error("标记预警为已处理失败", e);
            return Response.<Boolean>builder()
                    .code("500")
                    .data(false)
                    .info("标记失败：" + e.getMessage())
                    .build();
        }
    }

    // ==================== 综合健康评估 ====================
    
    @GetMapping("/score/{userId}")
    @Operation(summary = "计算健康评分", description = "根据用户健康数据计算综合健康评分")
    public Response<Integer> calculateHealthScore(@PathVariable Long userId) {
        try {
            Integer score = healthService.calculateHealthScore(userId);
            return Response.<Integer>builder()
                    .code("200")
                    .data(score)
                    .info("计算成功")
                    .build();
        } catch (Exception e) {
            log.error("计算健康评分失败", e);
            return Response.<Integer>builder()
                    .code("500")
                    .data(null)
                    .info("计算失败：" + e.getMessage())
                    .build();
        }
    }

    @GetMapping("/risk/{userId}")
    @Operation(summary = "评估健康风险", description = "评估用户的健康风险等级")
    public Response<String> assessHealthRisk(@PathVariable Long userId) {
        try {
            String riskLevel = healthService.assessHealthRisk(userId);
            return Response.<String>builder()
                    .code("200")
                    .data(riskLevel)
                    .info("评估成功")
                    .build();
        } catch (Exception e) {
            log.error("评估健康风险失败", e);
            return Response.<String>builder()
                    .code("500")
                    .data(null)
                    .info("评估失败：" + e.getMessage())
                    .build();
        }
    }
}